use std::fs;
use std::path::{Path, PathBuf};
use image::{DynamicImage, ImageResult, load_from_memory};
use crate::common::change_extension;
use crate::error::Res;

pub fn convert_images<P: AsRef<Path>>(source_path: P, source_format: &str, target_format: &str) -> Res<()> {
    fs::create_dir_all(&source_path)?;
    let mut paths = Vec::new();
    collect_image_paths(&source_path, &mut paths, source_format);

    for path in paths {
        let image = load_image(&path)?;
        let new_path = change_extension(&path, target_format);
        image.save(&new_path)?;
    }

    Ok(())
}

fn collect_image_paths<P: AsRef<Path>>(path: P, paths: &mut Vec<PathBuf>, source_format: &str) {
    if let Ok(entries) = fs::read_dir(path) {
        for entry in entries {
            if let Ok(entry) = entry {
                let path = entry.path();
                if path.is_file() {
                    if path.extension().and_then(|ext| ext.to_str()) == Some(source_format) {
                        paths.push(path);
                    }
                } else if path.is_dir() {
                    collect_image_paths(&path, paths, source_format);
                }
            }
        }
    }
}

fn load_image<P: AsRef<Path>>(path: P) -> ImageResult<DynamicImage> {
    let data = fs::read(path)?;
    load_from_memory(&data)
}


